/*!
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *
 *    Author: flareguner
 *    E-Mail: flareguner@gmail.com
 *    Years: 2010-2010
 */

#include "tooltip.h"
#include <QtGui/QClipboard>
#include <QtGui/QToolTip>
#include <QApplication>
#include <QDebug>
#include <QApplication>
#include <QDesktopWidget>

static const int tooltip_width = 640; // 640px ought to be enough for anybody ;)
// TODO auto-detect active screen width.

static const int tooltip_hide_timeout = 5000; // 5sec
// TODO move to Settings dialog.

ToolTip::ToolTip(QObject *parent) :
    QObject(parent),
    m_clipboard(qApp->clipboard()),
    m_cursor_pos_locked(false),
    m_hide_timer(this)
{
    m_hide_timer.setSingleShot(true);
    connect(m_clipboard, SIGNAL(selectionChanged()), this, SLOT(updateCursorPos()));
    connect(&m_hide_timer, SIGNAL(timeout()), this, SLOT(slotHideToolTip()));
}


void ToolTip::showTooltipText(const QString &text_){
    QString text;
    QFontMetrics fm(QToolTip::font());
    QStringList lines = text_.split(QChar('\n'));
    foreach (const QString &line_, lines) {
        QStringList words = line_.simplified().split(QRegExp("\\s+"), QString::SkipEmptyParts);
        if (words.isEmpty())
            continue;

        QString line;
        foreach (const QString &word, words) {
            QString tmp = line;
            if (!tmp.isEmpty())
                tmp += " ";
            tmp += word;
            if (fm.width(tmp) >= tooltip_width) {
                if (!line.isEmpty()) {
                    if (!text.isEmpty())
                        text += "\n";
                    text += line;
                    line = word;
                    continue;
                }
            }
            line = tmp;
        }
        if (!line.isEmpty()) {
            if (!text.isEmpty())
                text += "\n";
            text += line;
        }
    }
    if (text.isEmpty())
        return;

    QToolTip::showText(m_cursor_pos,text);
    if (tooltip_hide_timeout)
        m_hide_timer.start(tooltip_hide_timeout);
}

void ToolTip::setCursorPositionLocked(bool b){
    m_cursor_pos_locked = b;
}

void ToolTip::updateCursorPos(){
    if(!m_cursor_pos_locked)
        m_cursor_pos = QCursor::pos();
}

void ToolTip::slotHideToolTip() {
    QToolTip::hideText();
}

